// 核心是通过 AbortController API来取消请求 https://developer.mozilla.org/zh-CN/docs/Web/API/AbortController/AbortController
import type { AxiosRequestConfig } from 'axios';
import { generateReqKey } from './commonFuns';
/**
 * 用于存储控制器
 */
const pendingMap = new Map<string, AbortController>();

class AbortAxios {
	addPending(config: AxiosRequestConfig) {
		this.removePending(config);
		const url = generateReqKey(config);
		const abortController = new AbortController();
		config.signal = abortController.signal;
		if (!pendingMap.has(url)) {
			pendingMap.set(url, abortController);
		}
	}

	removePending(config: AxiosRequestConfig) {
		const url = generateReqKey(config);
		if (pendingMap.has(url)) {
			const abortController = pendingMap.get(url);
			abortController?.abort();
			pendingMap.delete(url);
		}
	}

	removeAllPending() {
		pendingMap.forEach((abortController) => {
			abortController.abort();
		});
		this.clear();
	}

	clear() {
		pendingMap.clear();
	}
}

export default AbortAxios;
